package com.yhc.user.server.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yhc.user.server.service.IUserCacheService;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * 数据库公共字段填充
 */
@Configuration
public class MapperObjectHandler implements MetaObjectHandler {

    @Autowired
    IUserCacheService userCacheService;

    private static final Boolean DEFAULT_INIT_DELETED_VALUE = false;
    private static final int DEFAULT_INIT_VERSION_VALUE = 1;

    @Override
    public void insertFill(MetaObject metaObject) {
        String username = userCacheService.getUser() == null ? "default" : userCacheService.getUser().getName();

        this.setFieldValByName("deleted", DEFAULT_INIT_DELETED_VALUE, metaObject);
        this.setFieldValByName("version", DEFAULT_INIT_VERSION_VALUE, metaObject);

        if (this.getFieldValByName("createBy", metaObject) == null) {
            this.setFieldValByName("createBy", username, metaObject);
        }
        if (this.getFieldValByName("createTime", metaObject) == null) {
            this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        }
        this.setFieldValByName("updateBy", username, metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String username = userCacheService.getUser() == null ? "default" : userCacheService.getUser().getName();

        Object versionObj = this.getFieldValByName("version", metaObject);
        int version = Integer.valueOf(versionObj.toString()) + 1;
        this.setFieldValByName("version", version, metaObject);

        if (this.getFieldValByName("updateBy", metaObject) == null) {
            this.setFieldValByName("updateBy", username, metaObject);
        }

        // 强制更新updateTime，有些是查询后进行更新，updateTime此时有值则不会进行更新
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    }

}